package com.controller;

import com.services.IUserServices;
import com.services.impl.UserServicesImpl;
import net.sf.json.JSONObject;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

/**
 * @Program: exam
 * @ClassName: SelectBlackServletController
 * @Description: 批量恢复黑名单用户
 * @Author: li
 * @Create: 2019-07-24 08:32
 */
@WebServlet("/SelectBlackServlet")
public class SelectBlackServletController extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // 设置响应格式
        response.setContentType("application/json;charset=UTF-8");
        request.setCharacterEncoding("utf-8");
        response.setCharacterEncoding("utf-8");

        Map<String, Object> result = new HashMap<>();
        
        try {
            String emailsStr = request.getParameter("emails");
            
            // 参数校验
            if (emailsStr == null || emailsStr.trim().isEmpty()) {
                result.put("code", 400);
                result.put("msg", "参数错误：emails不能为空");
                response.getWriter().write(JSONObject.fromObject(result).toString());
                return;
            }

            // 打印日志
            System.out.println("批量恢复用户 - emails: " + emailsStr);

            String[] emails = emailsStr.split(",");
            IUserServices services = new UserServicesImpl();

            // 执行批量恢复
            for (String email : emails) {
                if (email != null && !email.trim().isEmpty()) {
                    services.changStatus(email.trim(), 1); // 1表示正常状态
                }
            }

            // 返回成功响应
            result.put("code", 0);
            result.put("msg", "批量恢复成功");
            
        } catch (Exception e) {
            e.printStackTrace(); // 打印详细错误信息
            result.put("code", 500);
            result.put("msg", "批量恢复失败：" + e.getMessage());
        }
        
        String jsonResult = JSONObject.fromObject(result).toString();
        System.out.println("响应结果：" + jsonResult);
        response.getWriter().write(jsonResult);
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doGet(request, response);
    }
}
